<?php

/*
*
*  3DES加密类
*  加密模式：CBC
*  注:需开启mcrypt扩展;CBC模式下需要iv,其他模式忽略
*	   
*/ 

class DESModel{
	private $key = '6B62F058EA1FD36B9BD32CA1B1F487CB065A8E8ED31685BA';

	//加密 CBC
	public  function encrypt($value) {
		$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
		$iv = base64_decode('AQIDBAUGBwg=');
		$key = pack('H48', $this->key);//key长度转换成24位
		$value = $this->PaddingPKCS7($value);//加密之前需填充 和java有别
		mcrypt_generic_init ($td, $key, $iv);
		$ret = base64_encode (mcrypt_generic($td, $value));
		mcrypt_generic_deinit ($td);
		mcrypt_module_close ($td);	 
		return $ret;
	}
	 
	//解密
	public  function decrypt($value) {
		$td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
		$iv = base64_decode('AQIDBAUGBwg=');
		$key = pack ('H48',$this->key);
		mcrypt_generic_init ($td, $key, $iv);
		$ret = trim (mdecrypt_generic ($td, base64_decode($value)));
		$ret = $this->UnPaddingPKCS7($ret);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		return $ret;
	}
	 
	private  function PaddingPKCS7($data) {
		$padlen = 8 - strlen($data) % 8;
		for($i = 0; $i < $padlen; $i++) $data .= chr($padlen);
		return $data;
	}
	 
	private  function UnPaddingPKCS7($data) {
		$padlen = ord(substr($data, (strlen($data)-1), 1));
		if ($padlen > 8) return $data;
		for($i = -1*($padlen-strlen($data)); $i < strlen ($data); $i++) {
			if(ord(substr($data, $i, 1)) != $padlen) return false;
		}
		return substr($data, 0, -1*($padlen - strlen($data)));
	}
	 
}	 
?>


